package com.example.pt.controller;

import cn.hutool.core.io.FileUtil;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.pt.dto.UserTransferStatsDTO;
import com.example.pt.entity.User;
import com.example.pt.repository.UserRepositories;
import com.example.pt.service.UserService;
import com.example.pt.service.UserTransferStatsService;
import com.example.pt.utils.DownloadUrlUtils;
import com.example.pt.utils.JWTUtil;
import com.example.pt.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 用户控制器
 */
@RestController
@RequestMapping("/api/users")
@CrossOrigin(origins = "*")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserTransferStatsService userTransferStatsService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private UserRepositories userRepositories;

    @Autowired
    private DownloadUrlUtils downloadUrlUtils;

    private static final String ROOT_PATH = System.getProperty("user.dir") + File.separator + "files";

    /**
     * 根据用户名搜索用户
     *
     * @param info 用户名关键字
     * @return 搜索结果
     */
    @GetMapping("/search")
    public ResponseEntity<?> searchByUsername(@RequestParam String info) {
        List<User> users = userService.searchByUsername(info);

        Map<String, Object> response = new HashMap<>();

        if (users == null || users.isEmpty()) {
            response.put("message", "没有相关用户，请更换用户名重新搜索");
            return ResponseEntity.ok(response);
        }

        response.put("message", "找到" + users.size() + "个结果");
        response.put("users", users);
        return ResponseEntity.ok(response);
    }

    /**
<<<<<<< HEAD
     * 获取用户的总上传量和总下载量
     *
     * @return 包含总上传量和总下载量的响应
     */
    @GetMapping("/transfer-stats")
    public ResponseEntity<?> getUserTransferStats( @RequestHeader Map<String, String> headers) {
        String token = headers.get("token");
        if (token == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("缺少认证信息");
        }
        int userId;
        Map<String, Object> result = new HashMap<>();

        try {
            DecodedJWT decodedJWT = JWTUtil.verifyToken(token);
             userId= decodedJWT.getClaim("uid").asInt();

            UserTransferStatsDTO statsDTO = userTransferStatsService.getUserTotalTransferStats(userId);

            if (statsDTO != null && statsDTO.getUserId() != null) {
                result.put("downloaded",statsDTO.getTotalDownloaded());
                result.put("uploaded",statsDTO.getTotalUploaded());
                result.put("ratio",statsDTO.getRatio());
                result.put("virtual_uploaded",statsDTO.getTotalVirtualUploaded());
                result.put("virtual_downloaded",statsDTO.getTotalVirtualDownloaded());

                return ResponseEntity.ok(Result.success(result, "返回用户上传下载量统计数据"));
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body("用户统计数据获取失败");

            }
        } catch (JWTVerificationException e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("无效的Token");
        }
    }

    //更新用户个人信息
    @PutMapping("/updateInfo")
    public ResponseEntity<?> updateUserInfo(
            @RequestHeader Map<String, String> headers,
            @RequestParam(required = false) String password,
            @RequestParam(required = false) String confirmPassword,
            @RequestParam(required = false) String email,
            @RequestParam(required = false) String userName
    ) {
        // 提取和验证JWT Token
        String token = headers.get("token");
        if (token == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("缺少认证信息");
        }

        try {
            DecodedJWT decodedJWT = JWTUtil.verifyToken(token);
            int userId = decodedJWT.getClaim("uid").asInt();

            // 根据userId查找用户
            User user = userService.searchByUid(userId);
            if (user == null) {
                return ResponseEntity.notFound().build();
            }

            // 记录修改的字段
            List<String> modifiedFields = new ArrayList<>();

            // 密码验证
            if (password != null && !password.isEmpty()) {
                if (!password.equals(confirmPassword)) {
                    return ResponseEntity.badRequest().body("两次输入的密码不一致");
                }
                String encodedPassword = passwordEncoder.encode(password);
                user.setPassword(encodedPassword);
                modifiedFields.add(password);
            }

            // 用户名更新
            if (userName != null && !userName.isEmpty()) {
                user.setUsername(userName);
                modifiedFields.add(userName);
            }

            // 邮箱验证和更新
            if (email != null && !email.isEmpty()) {
                if (!email.matches("^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$")) {
                    return ResponseEntity.badRequest().body("邮箱格式不正确");
                }
                user.setEmail(email);
                modifiedFields.add(email);
            }
            userRepositories.save(user);

            // 如果没有修改任何字段
            if (modifiedFields.isEmpty()) {
                return ResponseEntity.badRequest().body("未提供需要修改的信息");
            }

            // 返回成功响应，包含修改的字段信息
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "修改成功");
            response.put("modifiedFields", modifiedFields);

            return ResponseEntity.ok(response);
        } catch (JWTVerificationException e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("无效的Token");
        }
    }


    //@RequestPart("file") MultipartFile file
    @PutMapping("/updatePhoto")
    public ResponseEntity<?> updatePhoto(
            @RequestHeader Map<String, String> headers,
            @RequestPart("file") MultipartFile file) {

        // 提取和验证Token
        String token = headers.get("token");
        if (token == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Result.fail("缺少认证信息"));
        }

        try {
            DecodedJWT decodedJWT = JWTUtil.verifyToken(token);
            int userId = decodedJWT.getClaim("uid").asInt();

            // 检查用户是否存在
            User user = userService.searchByUid(userId);
            if (user == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Result.fail("用户不存在"));
            }

            // 处理头像文件上传
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body(Result.fail("未上传头像文件"));
            }

            // 调用文件上传逻辑（建议抽离为独立服务）
            String avatarUrl;
            try {
                avatarUrl = uploadFile(file);
            } catch (IOException e) {
//                log.error("头像上传失败：{}", e.getMessage());
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                        .body(Result.fail("头像上传失败，请重试"));
            }

            // 更新用户头像并保存
            user.setHeadshot(avatarUrl);
            userRepositories.save(user);// 使用MyBatis的更新方法

            // 返回成功响应（包含新头像URL和操作信息）
            Map<String, Object> result = new HashMap<>();
            result.put("headshot", avatarUrl);
            result.put("message", "头像更新成功");
            result.put("userId", userId);

            return ResponseEntity.ok(Result.success(result, "操作成功"));
        } catch (JWTVerificationException e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Result.fail("无效的Token"));
        }
    }


    public String uploadFile(MultipartFile file) throws IOException {
        if (!FileUtil.exist("E:\\PrivateTracker\\HeadShot")) {
            FileUtil.mkdir("E:\\PrivateTracker\\HeadShot");  // 如果当前文件的父级目录不存在，就创建
        }

        String originalFilename = file.getOriginalFilename();  // 文件的原始名称
        String extName = FileUtil.extName(originalFilename); // 获取文件扩展名
        System.out.println("文件的原始名称：" + originalFilename);

        // 检查文件是否存在并处理重命名
        if (FileUtil.exist("E:\\PrivateTracker\\HeadShot" + File.separator + originalFilename)) {
            // 如果当前上传的文件已经存在了，那么这个时候就要重命名一个文件名称
            originalFilename =  originalFilename +"1."+ extName;
        }

        // 保存文件到本地
        File saveFile = new File("E:\\PrivateTracker\\HeadShot" + File.separator + originalFilename);
        System.out.println("文件的保存路径：" + saveFile.getAbsolutePath());
        file.transferTo(saveFile);  // 存储文件到本地的磁盘里面去

        // 返回保存的文件名
        return saveFile.getAbsolutePath();
    }


    @GetMapping("/userInfo")
    public ResponseEntity<?> getUserInfo(
            @RequestHeader Map<String, String> headers) {
        // 提取和验证JWT Token
        String token = headers.get("token");
        if (token == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("缺少认证信息");
        }
        Map<String, Object> result = new HashMap<>();

        try {
            DecodedJWT decodedJWT = JWTUtil.verifyToken(token);
            int userId = decodedJWT.getClaim("uid").asInt();

            // 根据userId查找用户
            User user = userService.searchByUid(userId);
            if (user == null) {
                return ResponseEntity.notFound().build();
            }
            result.put("uid",user.getUid());
            result.put("userName",user.getUsername());
            result.put("points",user.getPoints());
            result.put("level",user.getLevel());

            String headShotUrl = downloadUrlUtils.generateDownloadLink(userId);

            result.put("headShot",headShotUrl);
            result.put("userType",user.getUsertype());
            result.put("email",user.getEmail());
            return ResponseEntity.ok(Result.success(result, "成功返回所有"));

        } catch (JWTVerificationException e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Result.fail("无效的Token"));
        }
    }

    @GetMapping("/userInfoUid/{userId}")
    public ResponseEntity<?> getUserInfoUID(
            @RequestHeader Map<String, String> headers,
            @PathVariable int userId) {

        System.out.println("/*************************************************************************************");
        // 提取和验证JWT Token
        String token = headers.get("token");
        if (token == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("缺少认证信息");
        }
        Map<String, Object> result = new HashMap<>();

        try {
            DecodedJWT decodedJWT = JWTUtil.verifyToken(token);
            // 根据userId查找用户
            User user = userService.searchByUid(userId);
            if (user == null) {
                return ResponseEntity.notFound().build();
            }
            result.put("uid",user.getUid());
            result.put("userName",user.getUsername());
            result.put("points",user.getPoints());
            result.put("level",user.getLevel());

            String headShotUrl = downloadUrlUtils.generateDownloadLink(userId);

            result.put("headShot",headShotUrl);
            result.put("userType",user.getUsertype());
            result.put("email",user.getEmail());
            return ResponseEntity.ok(Result.success(result, "成功返回所有"));

        } catch (JWTVerificationException e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Result.fail("无效的Token"));
        }
    }


    @GetMapping("/get/userInfo")
    public ResponseEntity<?> getUserInfo(@RequestHeader Map<String, String> header,
                                         @RequestParam int userId){

        DecodedJWT decodedJWT;
        String token = header.get("token");

        // 如果没有找到token头，尝试从Authorization头获取
        if ((token == null || token.isEmpty()) && (header.containsKey("authorization") || header.containsKey("Authorization"))) {
            String authHeader = header.getOrDefault("authorization", header.getOrDefault("Authorization", ""));
            // 检查是否包含Bearer前缀
            if (authHeader != null && !authHeader.isEmpty()) {
                if (authHeader.startsWith("Bearer ")) {
                    token = authHeader.substring(7); // 移除"Bearer "前缀
                } else {
                    token = authHeader;
                }
                System.out.println("从Authorization头提取token: " + token);
            }
        }

        if (token == null || token.isEmpty()) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "未提供有效的认证信息");
            return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);
        }

        if(userService.searchByUid(userId) != null) {
            User user = userService.searchByUid(userId);

            Map<String, Object> result = new HashMap<>();
            result.put("status", "success");
            String newToken = JWTUtil.generateToken(user.getUsertype(),userId);
            result.put("token", newToken);
            result.put("userId", userId);
            result.put("username", user.getUsername());
            String headShotUrl = downloadUrlUtils.generateDownloadLink(userId);
            result.put("headShot",headShotUrl);
            return new ResponseEntity<>(result, HttpStatus.OK);
        }
        Map<String, Object> response = new HashMap<>();
        response.put("status", "fail");
        response.put("message", "失败");
        return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);

    }
}
